<template>
  <div class="login-container-1">
    <img class="bg-img" v-lazy="loginBg" alt="login-bg" />
    <div v-if="isWxlogin">
      <div class="login-logo" @click="toHome">
        <i>
          <img v-lazy="logoImg" alt="Logo" />
        </i>
      </div>
      <div class="login-footer">
        <span> &copy; 2022 Pluse.Vip Inc. All rights reserved.</span>
        <span> <a href="/follow?docs=user" class="footer-span-a">服务条款</a></span>
        <span> <a href="/follow?docs=privacy" class="footer-span-a">隐私协议</a></span>
      </div>
      <div class="login-warp">
        <div class="login-left">
          <div class="login-left-center">
            <div class="login-left-center-top">
              <p>享受世界，尽在视易</p>
            </div>
            <div class="login-left-center-btm">
              <span class="feature-item">
                <i>
                  <v-icon name="duihao2" />
                </i>
                <span>影视</span>
              </span>
              <span class="feature-item">
                <i>
                  <v-icon name="duihao2" />
                </i>
                <span>剧集</span>
              </span>
              <span class="feature-item">
                <i>
                  <v-icon name="duihao2" />
                </i>
                <span>流媒体</span>
              </span>
            </div>
          </div>
        </div>
        <div class="login-card">
          <div class="card-warp">
            <main class="ScNRM">
              <div class="login-title">
                <h1>登录你的视易账户</h1>
              </div>
              <div class="login-content">
                <div class="login-input">
                  <div class="input-warp">
                    <div class="input-area">
                      <div class="input-item">
                        <t-input
                          :maxlength="11"
                          v-model="formDatas.mobile"
                          placeholder="请输入手机号"
                        >
                          <template #prefix-icon> <t-icon name="mobile" size="24px" /></template>
                        </t-input>
                      </div>
                      <div class="input-item" v-if="mobileIsCheck">
                        <t-input :maxlength="6" v-model="formDatas.code" placeholder="请输入验证码">
                          <template #prefix-icon> <t-icon name="lock-on" size="24px" /> </template>
                          <template #suffix
                            ><button
                              class="code-btn"
                              @click="handleGetCaptcha()"
                              v-bind:disabled="countdown > 0"
                            >
                              {{ countdown > 0 ? `${countdown}秒后重新获取` : '获取验证码' }}
                            </button></template
                          >
                        </t-input>
                      </div>
                      <div class="login-button">
                        <div class="action-btn" @click="mobileLogin()">
                          <div class="primary-button">登录</div>
                        </div>
                      </div>
                      <div class="protocol">
                        点击「登录」表示已阅读并同意<a href="/follow?docs=user">《服务条款》</a>和<a
                          href="/follow?docs=privacy"
                          >《隐私协议》</a
                        >
                      </div>
                    </div>
                  </div>
                </div>
              </div>
              <div class="login-to-wx">
                <t-divider>其他方式</t-divider>
                <div class="login-to-wx-btn">
                  <button class="wx-button" @click="toWx">
                    <t-icon name="logo-wechat" style="color: #07c160; margin-right: 10px" />
                    微信登录
                  </button>
                  <button class="mini-button" @click="toMini"></button>
                </div>
              </div>
            </main>
          </div>
        </div>
      </div>
    </div>
    <div v-if="!isWxlogin">
      <div class="modal">
        <div class="modal-bg"></div>
        <div class="wx-scan-login">
          <div class="modal-title">
            <h3>使用微信扫码登录</h3>
            <span class="closeBtn" style="cursor: pointer">
              <t-icon name="close" size="24px" @click="toMobile" />
            </span>
          </div>
          <div class="scan-content" style="width: 360px">
            <div class="content-wrap">
              <div class="content">
                <img
                  :src="imgSrc"
                  alt="scan"
                  style="width: 170px; height: 170px"
                  v-show="scanStatus === 'noscan'"
                />
                <img
                  src="../../assets/img/scan_success.svg"
                  alt="scan"
                  style="width: 170px; height: 170px"
                  v-show="scanStatus === 'success'"
                />
                <img
                  src="../../assets/img/error.svg"
                  alt="scan"
                  style="width: 170px; height: 170px"
                  v-show="scanStatus === 'error'"
                />
              </div>
              <span class="no_scan" @click="getScanCode()" v-if="wxScanType === 'wx'"
                >无法显示二维码？</span
              >
              <span class="no_scan" @click="toMini()" v-if="wxScanType === 'mini'"
                >无法显示二维码？</span
              >
            </div>
            <h4 v-if="wxScanType === 'wx'">
              扫码 <strong>关注「vsae 视易」</strong>公众号完成登录
            </h4>
            <h4 v-if="wxScanType === 'mini'">使用 <strong>小程序扫码</strong> 完成登录</h4>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { useThemeStore, useUserStore } from '@/store'
import router from '@/router'
import { checkLoginStatusWebSocket, checkLoginStatusWebSocket1 } from '@/utils/websocket'
import { loginWithMobile, getWeChatQrCode, getMiniProgramQrCode } from '@/api/login'
import { MessagePlugin } from 'tdesign-vue-next'
import { useGlobalStore } from '@/store'
const darkLogo = 'https://static.pluse.vip/assets/logo-dark.png'
const lightLogo = 'https://static.pluse.vip/assets/logo.png'
const personImgDark = 'https://static.pluse.vip/assets/bg-dark.webp'
const personImg = 'https://static.pluse.vip/assets/bg.webp'
const globalStore = useGlobalStore()
const userStore = useUserStore()
const formDatas = ref({
  mobile: '',
  code: ''
})

const wxTicket = ref('')
const imgSrc = ref('')
const socket = ref(null)
// 初始化获取路由参数
onMounted(() => {
  const route = useRoute()
  const mobile = route.query.mobile
  const type = route.query.type
  if (type === 'wx') {
    isWxlogin.value = false
    getScanCode()
  } else {
    isWxlogin.value = true
  }
  if (mobile) {
    formDatas.value.mobile = mobile
  }
})
const isWxlogin = ref(true)
const scanStatus = ref('')
const wxScanType = ref('')
const mobileIsCheck = computed(() => {
  //正则校验手机号
  if (
    !/^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/.test(
      formDatas.value.mobile
    )
  ) {
    return false
  } else {
    return true
  }
})
//主题store
const themeStore = useThemeStore()
// isDarkMode 是判断当前主题模式
const isDarkMode = computed(() => {
  // 假设你有一个 `themeStore` 状态管理模块，
  // 并且 `mode` 属性表示当前主题模式。
  return themeStore.mode === 'dark'
})
// 监听本地存储的主题模式变化
const loginBg = computed(() => {
  return isDarkMode.value ? personImgDark : personImg
})
const logoImg = computed(() => {
  return isDarkMode.value ? darkLogo : lightLogo
})
const toHome = () => {
  router.push('/')
}
const toWx = () => {
  isWxlogin.value = false
  router.push({ path: '/login', query: { type: 'wx' } })
  getScanCode()
}

const toMobile = () => {
  isWxlogin.value = true
  router.push({ path: '/login', query: { type: 'mobile' } })
}

/**
 * 手机号登录
 */
const mobileLogin = async () => {
  //判断手机号和验证码是否为空
  if (formDatas.value.code.length != 6) {
    MessagePlugin.error('请输入正确的验证码')
    return
  }
  let data = {
    mobile: formDatas.value.mobile,
    verCode: formDatas.value.code,
    promotionCode: localStorage.getItem('uid')
  }
  const res = await loginWithMobile(data)
  if (res.code === 200) {
    userStore.login(res.data.token).then(userInfo => {
      if (userInfo) {
        router.push('/')
      }
    })
  }
}
/**
 * 获取验证码
 */
const handleGetCaptcha = () => {
  globalStore.getCaptcha(formDatas.value.mobile)
}

const countdown = computed(() => {
  return globalStore.countdown
})

const handleScanStatus = status => {
  if (status === 'success') {
    MessagePlugin.success('扫码成功')
    scanStatus.value = 'success'
  } else if (status === 'error') {
    MessagePlugin.error('扫码失败，请重试!')
    scanStatus.value = 'error'
  }
  if (status === 'login_success') {
    MessagePlugin.success('登录成功')
    isWxlogin.value = true
  }
}

const toMini = async () => {
  wxScanType.value = 'mini'
  scanStatus.value = 'noscan'
  imgSrc.value = ''
  // 获取小程序二维码
  isWxlogin.value = false
  const uid = localStorage.getItem('uid')
  const params = {
    promotionCode: uid,
    type: 'login',
    myPromotionCode: ''
  }
  try {
    const res = await getMiniProgramQrCode(params)
    if (res.code !== 200) {
      MessagePlugin.error('获取小程序二维码失败')
      scanStatus.value = 'error'
      return
    }
    wxTicket.value = res.data.ticket
    imgSrc.value = `data:image/jpg;base64,${res.data.image}`
    checkLoginStatusWebSocket1(res.data.ticket, handleScanStatus)
  } catch (error) {
    //console.log(error)
  }
}
/**
 * 获取微信二维码
 */
const getScanCode = async () => {
  wxScanType.value = 'wx'
  scanStatus.value = 'noscan'
  imgSrc.value = ''
  const uid = localStorage.getItem('uid')
  const params = {
    promotionCode: uid,
    type: 'login',
    myPromotionCode: ''
  }
  try {
    const imageData = await getWeChatQrCode(params)
    if (imageData.code !== 200) {
      MessagePlugin.error('获取微信二维码失败')
      scanStatus.value = 'error'
      return
    }
    wxTicket.value = imageData.data.ticket
    imgSrc.value = `data:image/jpg;base64,${imageData.data.image}`
    // 连接 WebSocket
    //console.log('登录ticket' + imageData.data.ticket)
    checkLoginStatusWebSocket1(imageData.data.ticket, handleScanStatus)
  } catch (error) {
    //console.log(error)
  }
}

onBeforeUnmount(() => {
  if (socket.value) {
    socket.value.close()
  }
})
</script>
<style lang="scss" src="./index.scss" scoped></style>
